<template>
  <div class="eq_container eq_dashboard_container">
    <div class="app-container detail-head">
      <div class="top-block-frm">
        <div class="tt">
          {{ id ? '编辑产品' : '新增产品' }}
          <div>
            <el-button size="mini" type="success" icon="el-icon-check" @click="toSave">保存</el-button>
            <el-button v-if="id" size="mini" type="danger" icon="el-icon-delete" @click="toDelete">删除</el-button>
          </div>
        </div>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="small" v-loading="loading">
        <!-- 基本信息 -->
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :md="12">
              <el-form-item label="产品名" prop="name">
                <el-input v-model="form.name" placeholder="请输入产品名称" clearable />
              </el-form-item>
              <el-form-item label="主标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入主标题" clearable />
              </el-form-item>
              <el-form-item label="货币" prop="currency">
                <el-select v-model="form.currency" placeholder="请选择货币" style="width: 100%;">
                  <el-option
                    v-for="item in currencyList"
                    :key="item.symbol"
                    :label="item.symbol"
                    :value="item.symbol"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="缩略图" prop="thumbnail_image">
                <el-upload
                  class="upload-demo"
                  action=""
                  :http-request="(file)=>handleHttpRequest(file, 'thumbnail')"
                  list-type="picture-card"
                  :limit="1"                  
                  :file-list="thumbnailList"     
                  :on-remove="handleRemoveThumbnail"
                  accept=".jpg,.png,.jpeg"
                 >
                 <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>

            <el-col :md="12">
              <el-form-item v-if="id" label="状态">
                <el-tag :type="statusTagType" effect="light">
                  {{ statusText }}
                </el-tag>
                <el-button
                  v-if="form.status === 0"
                  size="small"
                  class="ttrtbtn"
                  type="success"
                  style="margin-left: 10px;"
                  icon="el-icon-upload2"
                 @click="publish"
                >上架发布
                </el-button>
                <el-button
                  v-if="form.status === 1"
                  size="small"
                  class="ttrtbtn"
                  type="default"
                  style="margin-left: 10px;"
                 icon="el-icon-download"
                 @click="unPublish"
                >下架隐藏
                </el-button>
              </el-form-item>
             <!-- 新增时自己选状态 -->
              <el-form-item v-else label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                  <el-option
                    v-for="item in productStatusOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="副标题" prop="subtitle">
                <el-input v-model="form.subtitle" placeholder="请输入副标题" clearable />
              </el-form-item>
              <el-form-item label="模板" prop="template_id" >
                <el-select v-model="form.template_id" placeholder="请选择模板" style="width: 100%;">
                  <el-option 
                    v-for="item in templateList" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                  />
                </el-select>
                <div>
                  <el-button type="text" icon="el-icon-circle-plus-outline" size="mini" @click="toAddTemplate">新增模板</el-button>
                </div>
              </el-form-item>
               <el-form-item label="最低价格" prop="lowest_price">
                <el-input-number v-model="form.lowest_price" :min="0" :step="0.01" />
              </el-form-item>
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="form.sort"
                  :min="0"
                  :max="9999"
                  label="请输入排序数字（可选）"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :md="24">
              <el-form-item label="产品主图" prop="images">
                <el-upload
                  class="upload-demo"
                  action=""
                  :http-request="(file)=>handleHttpRequest(file, 'product_images')"
                  list-type="picture-card"
                  multiple
                  :file-list="imageList"
                  :on-remove="handleRemoveImage"
                  accept=".jpg,.png,.jpeg"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 产品内容描述 -->
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">内容描述</div>
          <!-- <el-form-item label="内容页面URL" prop="content_url">
            <el-input v-model="form.content_url" placeholder="请输入内容页面URL" clearable />
          </el-form-item> -->
          <rc-editor
            api-key=""
            v-model="form.content"
          />
        </el-card>

        <!-- 变体信息 -->
        <el-card shadow="never" class="mb-2" v-if="id">
          <div slot="header" class="left-title">变体配置</div>
          <div>
            <div
              class="ctrl-bar"
              style="justify-content: space-between; display: flex; font-size: 14px; align-items: center"
            >
            <label>符合条件的 {{ list.length }} 条记录</label>
            <div>
              <el-button type="primary" size="mini" icon="ti ti-table-plus" @click="toNew">
                新增变体
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="list"
            border
            size="mini"
          >
            <el-table-column label="ID" align="left" prop="id" width="70" />
            <el-table-column label="变体名" align="left" prop="name" min-width="120" />
            <el-table-column label="主标题" align="left" prop="title" min-width="150" />
            <el-table-column label="副标题" align="left" prop="subtitle" min-width="150" />
            <el-table-column label="主图" align="left" min-width="200">
              <template slot-scope="scope">
                <div class="image-list">
                  <img
                    v-for="(url, index) in parseImageList(scope.row.images)"
                    :key="index"
                    :src="url"
                    class="product-image"
                    @click="handlePreview(url)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="缩略图" align="left" width="120">
              <template slot-scope="scope">
                <img
                  v-if="parseThumbnail(scope.row.thumbnail_image)"
                  :src="parseThumbnail(scope.row.thumbnail_image)"
                  class="thumbnail-image"
                  @click="handlePreview(parseThumbnail(scope.row.thumbnail_image))"
                />
                <span v-else>—</span>
              </template>
            </el-table-column>
            <el-table-column label="原价" align="left" prop="original_price" width="90" />
            <el-table-column label="折扣价" align="left" prop="discount_price" width="90" />
            <el-table-column label="货币" align="left" prop="currency" width="80" />
            <el-table-column label="状态" align="left" prop="status" width="90">
              <template slot-scope="scope">
                <el-tag size="mini" :type="scope.row.status_cls" :key="scope.row.id" >
                  {{ scope.row.status_txt }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="left" prop="create_time" width="160" />
            <el-table-column label="操作" width="150" fixed="right" align="left">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="ti ti-edit"
                  @click="toEdit(scope.row)"
                >编辑详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 图片预览弹框 -->
          <el-dialog
            title="图片预览"
            :visible.sync="previewVisible"
            width="40%"
            :show-close="true"
            :close-on-click-modal="true"
          >
            <div style="text-align:center;">
              <img
                :src="previewImage"
                alt="预览图"
                style="max-width:100%; max-height:80vh; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.2);"
              />
            </div>
          </el-dialog>

          <!-- 新增 / 编辑变体弹框 -->
          <el-dialog
            :title="dialogEditMode === 'edit' ? '修改变体' : '新增变体'"
            :visible.sync="dialogEditVisible"
            width="800px"
            @close="dialogEditVisible = false"
            top="10vh"
          >
            <varient-edit
              :mode="dialogEditMode"
              :row-data="currentEditRow"
              :product-id="Number(id)"          
              @success="handleEditSuccess"
              @close="dialogEditVisible = false"
            />
            </el-dialog>
          </div>
        </el-card>

        <!-- 新增模板弹框 -->
        <el-dialog title="新增模板" :visible.sync="dialogVisible" width="600px" @close="dialogVisibleSales = false" :modal="false" top="20vh">
          <template-config
            :mode="dialogMode"
            :row-data="currentRow"
            @close="dialogVisible = false"
            @save-success="handleSaveSuccess"
          />
        </el-dialog>

      </el-form>
    </div>
  </div>
</template>

<script>
import { aliClientInit, ossFilePath } from '@/api/common'
import { getProductByID, editProductById ,getTemplateList} from '@/api/product'
import VarientConfig from '@/layout/components/varientConfig/index.vue'
import TemplateConfig from '@/layout/components/templateConfig/index.vue'
import RcEditor from '@/layout/components/Editor/index.vue'
import VarientEdit from '@/layout/components/varientConfig/edit.vue'
import { parseImageList, parseThumbnail } from '@/utils/common'

export default {
  name: 'ProductEdit',
  components: { 
    VarientConfig,
    TemplateConfig,
    RcEditor,
    VarientEdit
   },
  data() {
    return {
      id: '',
      loading: false,
      file_loading: false,
      AliClient: null,
      imageList: [],
      images: [],  // 存放主图 URL
      thumbnail_image: '' ,
      thumbnailList:[],
      templateList: [],
      statusText: '',     
      statusTagType: '', 
      dialogVisible: false,
      dialogMode: 'create',
      currentRow: null,
      previewVisible: false,
      previewImage: '',
      total:0,
      dialogEditVisible: false,
      currentEditRow: null,
      dialogEditMode: 'create',
      list:[],
      currencyList: this.hashmap.currencyList,
      productStatusOption: this.hashmap.productStatusOption,

      form: {
        name: '',
        title: '',
        subtitle: '',
        lowest_price: 0,
        status: 1,
        images: [],
        thumbnail_image: '',
        template_id: '',
        content: '',
        variants: [],
        content_url: '',   
        currency: 'USD',      
        sort: 0, 
      },
      
      rules: {
        name: [{ required: true, message: '请输产品名称', trigger: 'blur' }],
        lowest_price: [{ required: true, message: '请输最低价格', trigger: 'blur' }],
        template_id: [{ required: true, message: '请选择关联模板', trigger: 'change' }],
        currency: [{ required: true, message: '请选择货币', trigger: 'change' }],
        images: [{ required: true, message: '请上传主图', trigger: 'change', type: 'array' }],
      },
    }
  },

  watch: {
    '$route.query.id'(newId) {
      this.id = newId || null
      if (this.id) {
        this.getProductByID()
      }
    }
  },

  computed: {
  },

  created() {
    this.id = this.$route.query.id || null
    if (this.id) this.getProductByID()

    this.aliOssInit()
    this.getTemplateList()
  },

  methods: {
    parseImageList,
    parseThumbnail,

    async aliOssInit() {
      this.AliClient = await aliClientInit()
    },

    async handleHttpRequest(option, ftag) {
      const vm = this
      vm.disabled = true
      vm.file_loading = true
      const client = this.AliClient
      const file = option.file
      const random_name = ossFilePath(file.name)

      console.log('阿里云上传开始:', client, file)

      await client.put(random_name, file)
        .then((res) => {
          console.log('阿里云上传成功:', res)
          vm.file_loading = false
          vm.disabled = false

          if (ftag === 'product_images') {
            // ✅ 产品主图（多图上传）
            vm.imageList.push({
              url: res.url,
              name: random_name
            })
            vm.form.images.push(res.url)
          } 
          else if (ftag === 'thumbnail') {
            // ✅ 缩略图（单图上传）
            vm.thumbnailList = [{ url: res.url, name: random_name }]
            vm.form.thumbnail_image = res.url
          }

          vm.$nextTick(() => {
            vm.$refs.formRef && vm.$refs.formRef.validateField('images')
          })
 
          vm.$message.success('上传成功')
          return res.url
        })
        .catch((error) => {
          console.error('阿里云上传失败:', error)
          vm.file_loading = false
          vm.disabled = false
          vm.$message.error('上传失败，请重试')
        })
    },

    // 删除主图
    handleRemoveImage(file) {
      this.imageList = this.imageList.filter(f => f.url !== file.url)
      this.form.images = this.form.images.filter(url => url !== file.url)
      // 如果删到 0 张，可以重新标红
      if (this.form.images.length === 0) {
        this.$nextTick(() => {
          this.$refs.formRef && this.$refs.formRef.validateField('images')
        })
      }
    },

    // 删除缩略图
    handleRemoveThumbnail(file) {
      this.thumbnailList = []
      this.form.thumbnail_image = ''
    },

    getProductByID() {
      this.loading = true
      getProductByID({
       product_id: this.id
      }).then((res) => {
        if (res && res.code === 0 && res.data) {
          const data = res.data
          this.form = data
          this.form.thumbnail_image = Array.isArray(data.thumbnail_image)? data.thumbnail_image[0] || '': data.thumbnail_image || ''
          this.form.images = Array.isArray(data.images) ? data.images : []
          this.statusText=this.findJsonByKeyValue(this.productStatusOption, 'value', data.status).label || '',
          this.statusTagType=this.findJsonByKeyValue(this.productStatusOption, 'value', data.status).typeClass || '',
          //处理图片展示数据
          this.imageList = (data.images || []).map(url => ({ url }))
          this.thumbnailList = Array.isArray(data.thumbnail_image)
            ? data.thumbnail_image.map(url => ({ url }))
            : data.thumbnail_image
              ? [{ url: data.thumbnail_image }]
              : []

          //变体列表
          this.list = data._variant_list.map(item => ({
            ...item,
            status_txt: this.findJsonByKeyValue(this.productStatusOption, 'value', item.status).label || '',
            status_cls: this.findJsonByKeyValue(this.productStatusOption, 'value', item.status).typeClass || '',
          }))
        }
      }).finally(()=>{
        this.loading = false
      })
    },

    toSave() {
      const $this = this
      $this.$refs.formRef.validate(valid => {
        if (!valid) return
        $this.$confirm('确认提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          $this.loading = true
          const isEdit = !!$this.id

          const params = { ...$this.form }

          // 编辑时带上 product_id
          if (isEdit) {
            params.product_id = Number($this.id)
          }
          console.log('保存传参：', params)

          editProductById(params)
            .then((res) => {
              if (res && res.code === 0) {
                const newId = isEdit ? $this.id : (res.data && res.data.id)

                $this.$message.success(isEdit ? '修改成功' : '新增成功')

                if (!isEdit && newId) {
                  $this.$router.replace({
                    path: '/product/detail',
                    query: { id: newId }
                  })
                  $this.id = newId
                  $this.getProductByID()
                }

                if (isEdit) {
                  $this.getProductByID()
                }
              } else {
                $this.$message.error(res?.msg || (isEdit ? '修改失败' : '新增失败'))
              }
            })
            .finally(() => {
              $this.loading = false
            })
        }).catch(() => {})
      })
    },

    // 通用状态更新方法
    updateStatus (newStatus, confirmText, successMsg, afterSuccess) {
      if (!this.id) return

      this.$confirm(confirmText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        editProductById({
          product_id: Number(this.id),
          status: newStatus
        })
          .then(res => {
            if (res && res.code === 0) {
              if (newStatus == 1 ) {
                this.form.status = newStatus
              }
              this.$message.success(successMsg)

              if (typeof afterSuccess === 'function') {
                afterSuccess()
              }
            } else {
              this.$message.error(res?.msg || '操作失败')
            }
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {})
    },

    // 删除：status = 2
    toDelete () {
      this.updateStatus(2,'确认是否删除该产品？','删除成功',() => {
        this.$router.push({ path: '/product/list' })
      })
    },

     // 上架：status = 1
    publish () {
      this.updateStatus(1,'确认将该产品上架发布吗？','上架成功')
    },

    // 下架：status = 0
    unPublish () {
      this.updateStatus(0,'确认将该产品下架隐藏吗？','下架成功',() => {
        this.$router.push({ path: '/product/list' })
      })
    },

    getTemplateList(){
      getTemplateList({
        'page':1,
        'page_size':5000,
        'status':1
      }).then((res)=>{
        if(res){
          this.templateList = res.data.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
              key: item.id,
              type: item.id
            }
          })
        }
      })
    },

    toAddTemplate(){
      this.dialogMode = 'create'
      this.currentRow = null
      this.dialogVisible = true
    },

    handleSaveSuccess() {
      this.dialogVisible = false
      this.getTemplateList()
    },

    // 编辑变体子组件保存成功
    handleEditSuccess () {
      this.dialogEditVisible = false
      this.getProductByID()
    },

    handlePreview (url) {
      this.previewImage = url
      this.previewVisible = true
    },

    toNew () {
      this.dialogEditMode = 'create'
      this.currentEditRow = {}
      this.dialogEditVisible = true
    },
    toEdit (row) {
      this.dialogEditMode = 'edit'
      this.currentEditRow = { ...row }
      this.dialogEditVisible = true
    },

  }
}
</script>

<style scoped>
.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 8px;
  border-radius: 8px;
  border: 1px solid #eee;
}
.mb-2 { margin-bottom: 16px; }
.mt-2 { margin-top: 12px; }

.left-title{
  padding-left: 5px;
  border-left: 3px solid #4974e1;
}
</style>
